<template>
  <div class="purchasing">
    <div style="display: flex; justify-content: space-between">
      <div>
        <el-button size="mini" type="primary" plain @click="add">
			采购零件
		</el-button>
      </div>

      <div style="display: flex;">
		<el-select v-model="suppliersId" filterable remote placeholder="根据供应商搜索"
			:remote-method="getSuppliersList" :loading="suppliersLoading"
			@change="getAllGoods" clearable size="mini"
			@focus="getSuppliersList('')" style="width: 160px;">
			<el-option v-for="item in suppliersList" :key="item.id" :label="item.suppliersName" :value="item.id">
			</el-option>
		</el-select>
		<el-select v-model="userId" filterable remote placeholder="采购人"
			:remote-method="getUserList" :loading="userLoading" 
			@change="getAllGoods" clearable size="mini"
			@focus="getUserList('')" style="width: 120px;">
			<el-option v-for="item in userList" :key="item.id" :label="item.nickName" :value="item.id">
			</el-option>
		</el-select>
		<el-select v-model="paymentMethod" placeholder="结款方式" size="mini"
			@change="getAllGoods" style="width: 100px;">
			<el-option label="现金" :value="0"></el-option>
			<el-option label="月结" :value="1"></el-option>
		</el-select>
		<el-select v-model="orderStatus" placeholder="订单状态" size="mini"
			@change="getAllGoods" style="width: 100px;">
			<el-option label="已通过" :value="0"></el-option>
			<el-option label="待审核" :value="1"></el-option>
			<el-option label="未通过" :value="2"></el-option>
		</el-select>
        <el-button style="margin-left: 10px" size="mini" @click="reset" v-debounce>
			重置
		</el-button>
      </div>
    </div>

    <div class="goods-table">
      <el-table :data="tableData" v-loading="loading" border stripe
        style="width: 100%" height="100%" >
        <el-table-column prop="i" fixed="left" label="序号" width="50">
		</el-table-column>
		<el-table-column prop="suppliersName" label="供应商名称" width="220">
		</el-table-column>
		<el-table-column label="零件列表" width="80">
			<template slot-scope="scope">
				<el-button type="text" @click="partsOpen(scope.row)">点击查看</el-button>
			</template>
		</el-table-column>
		<el-table-column prop="userName" label="采购人" width="80">
		</el-table-column>
		<el-table-column prop="price" label="总金额" width="80">
		</el-table-column>
		<el-table-column prop="paymentMethod" label="结款方式" width="80">
			<template slot-scope="scope">
				<el-tag v-if="scope.row.paymentMethod === 0" effect="dark">现金</el-tag>
				<el-tag v-if="scope.row.paymentMethod === 1" 
					effect="dark" type="warning">
					月结
				</el-tag>
			</template>
		</el-table-column>
		<el-table-column prop="createTime" label="下单时间" width="100" >
		</el-table-column>
		<el-table-column prop="remark" label="采购备注" fit>
		</el-table-column>
		<el-table-column label="操作" width="145" fixed="right">
			<template slot-scope="scope">
<!-- 				<el-button size="mini" :type="oneKeyType(scope.row.receiptsStatus)"
					:disabled="oneKeyDisabled(scope.row)"
					@click="oneKeyWarehousing(scope.row)">
					{{oneKeyText(scope.row.receiptsStatus)}}
				</el-button> -->
				<el-button size="mini" type="text" 
					:disabled="applyDisabled(scope.row)"
					@click="applyShow(scope.row)">
					{{applyButtonText(scope.row)}}
				</el-button>
				<el-button size="mini" type="text" @click="details(scope.row.id)">
					详情
				</el-button>
				<el-button size="mini" type="text"
					@click="deletePurchasing(scope.row)" v-if="userInfo.roleId === '1'">
					删除
				</el-button>
			</template>
		</el-table-column>
      </el-table>
      <el-pagination background :current-page="currentPage" :page-size="pageSize" :total="total"
		@current-change="handleCurrentChange" @size-change="handleSizeChange"
        :page-sizes="[20, 50, 100]" layout="total, sizes, prev, pager, next, jumper">
      </el-pagination>
    </div>
	
	<!-- 查看零件列表弹窗 -->
	<el-dialog style="margin-top:0" :visible.sync="partsShow" width="85%" 
		:title="selectTitle" @close="partsClose">
		<div class="data-table">
			<el-table :data="selectPurchase.parts" border style="width: 100%"
				:max-height="500" :row-style="tableRow">
				<el-table-column prop="i" fixed="left" label="序号" width="50">
				</el-table-column>
				<el-table-column label="图片" width="115">
					<template slot-scope="scope">
						<el-image :src="READ_IMG_URL+scope.row.image" 
							style="width: 90px; height: 90px;"
							:preview-src-list="new Array(READ_IMG_URL+scope.row.image)">
						</el-image>
					</template>
				</el-table-column>
				<el-table-column prop="partName" label="零件名称" fit>
				</el-table-column>
				<el-table-column prop="model" label="零件型号" fit>
				</el-table-column>
				<el-table-column prop="devicesDescribe" label="产品描述" fit>
				</el-table-column>
				<el-table-column prop="remark" label="备注" fit>
				</el-table-column>
				<el-table-column prop="purchasePrice" label="采购单价" width="80">
				</el-table-column>
        <el-table-column prop="cost" label="上次单价" width="80">
          <template slot-scope="scope">
						<span v-if="scope.row.cost < scope.row.purchasePrice"
                  style="color: red;">
							{{scope.row.cost}}
						</span>
            <span v-else-if="scope.row.cost > scope.row.purchasePrice"
                  style="color: lawngreen;">
							{{scope.row.cost}}
						</span>
            <span v-else>{{scope.row.cost}}</span>
          </template>
        </el-table-column>
				<el-table-column prop="freight" label="运输费" width="80">
				</el-table-column>
				<el-table-column prop="isIncludeTax" label="是否含税" width="80">
					<template slot-scope="scope">
						<el-tag v-if="scope.row.isIncludeTax === 0">含税</el-tag>
						<el-tag v-if="scope.row.isIncludeTax === 1" type="danger">
							不含税
						</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="partCount" label="采购数量" width="80">
				</el-table-column>
				<el-table-column prop="totalPrice" label="总计" width="80">
				</el-table-column>
			</el-table>
		</div>
	</el-dialog>
	<!-- 审核弹窗 -->
	<el-dialog style="margin-top: 0" width="75%"
		:visible.sync="applyDialog" title="订单审核">
		<el-form inline label-position="top" :model="selectPurchase">
			<el-form-item label="订单编号" style="width: 450px;">
				<el-input v-model="selectPurchase.id" placeholder="订单编号" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="供应商" style="width: 450px;">
				<el-input :value="selectPurchase.suppliersName" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="采购人" style="width: 450px;" >
				<el-input :value="selectPurchase.userName" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="结款方式" style="width: 450px;">
				<el-select v-model="selectPurchase.paymentMethod" disabled style="width: 100%;">
					<el-option label="现金" :value="0"></el-option>
					<el-option label="月结" :value="1"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="总金额" style="width: 450px;">
				<el-input v-model="selectPurchase.price" type="number" placeholder="总金额" step="0.01" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="采购备注" style="width: 450px;">
				<el-input v-model="selectPurchase.remark" placeholder="备注" readonly>
				</el-input>
			</el-form-item>
			<el-form-item label="零件列表" style="width: 100%;">
				<div>
					<el-table :data="selectPurchase.parts" border style="width: 100%" :max-height="400" :row-style="tableRow">
						<el-table-column prop="i" fixed="left" label="序号" width="50">
						</el-table-column>
						<el-table-column label="图片" width="115">
							<template slot-scope="scope">
								<el-image :src="READ_IMG_URL+scope.row.image" 
									style="width: 90px; height: 90px;"
									:preview-src-list="new Array(READ_IMG_URL+scope.row.image)">
								</el-image>
							</template>
						</el-table-column>
						<el-table-column prop="partName" label="零件名称" fit>
						</el-table-column>
						<el-table-column prop="model" label="零件型号" fit>
						</el-table-column>
						<el-table-column prop="purchasePrice" label="采购单价" width="80">
						</el-table-column>
            <el-table-column prop="cost" label="上次单价" width="80">
              <template slot-scope="scope">
								<span v-if="scope.row.cost < scope.row.purchasePrice"
                      style="color: red;">
									{{scope.row.cost}}
								</span>
                <span v-else-if="scope.row.cost > scope.row.purchasePrice"
                      style="color: lawngreen;">
									{{scope.row.cost}}
								</span>
                <span v-else>{{scope.row.cost}}</span>
              </template>
            </el-table-column>
						<el-table-column prop="freight" label="运输费" width="80">
						</el-table-column>
						<el-table-column prop="isIncludeTax" label="是否含税" width="80">
							<template slot-scope="scope">
								<el-tag size="medium" v-if="scope.row.isIncludeTax === 0">
									含税
								</el-tag>
								<el-tag v-if="scope.row.isIncludeTax === 1" size="medium"
									color="#F67A7A" style="color: white">
									不含税
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column prop="partCount" label="采购数量" width="80">
						</el-table-column>
						<el-table-column prop="totalPrice" label="总计" width="80">
						</el-table-column>
					</el-table>
				</div>
			</el-form-item>
		</el-form>
		<div slot="footer" class="dialog-footer">
			<el-button type="danger" @click="applyOrders(2)" v-debounce>驳回</el-button>
		    <el-button type="success" @click="applyOrders(0)" v-debounce>通过</el-button>
		</div>
	</el-dialog>
  </div>
</template>

<script>
import warehouseApi from "../../../api/warehouse";
import userApi from "../../../api/user.js";
import config from '../../../api/apiURL.js';
export default {
  components: {},
  data() {
    return {
      READ_IMG_URL: config.READ_IMG_URL,
		userInfo: {},
      role1: false,
      role2: false,
      ordid: "", //采购id
      receiptsStatusValue: "",
      receiptsStatusList: [
        { value: "-1", label: "全部" },
        { value: "0", label: "已入库" },
        { value: "1", label: "待审核" },
        { value: "2", label: "入库失败" },
        { value: "3", label: "待财务审核" },
      ],
      //采购订单列表
      options3: [
        { value: "选项1", label: "黄金糕" },
        { value: "选项2", label: "双皮奶" },
        { value: "选项3", label: "蚵仔煎" },
        { value: "选项4", label: "龙须面" },
        { value: "选项5", label: "北京烤鸭" },
      ],
      value3: "",
      //供应商列表
      options2: [
        { partName: "小马", model: "Y780" },
        { partName: "中马", model: "Y880" },
        { partName: "大马", model: "Y980" },
      ],
      loading2: false,
      value2: "",
      suppliers: {
        suppliersId: "", //供应商id
        suppliersName: "", //供应商名称
        suppliersAddress: "", //供应商地址
        suppliersPhone: "", //供应商电话
      },
      //搜索框的值
      input: "",
      // 图片预览
      srcList: [],
      srcList2: [],
      //修改按钮状态
      applyButton: 0, //0是新增 1是修改，2是申请修改
      // 上传图片文件
      selectedFile: null,
      //判断用户点击的是合同还是保密协议
      htdz: "",
      // 合同地址
      imageUrl: "",
      // 保密协议地址
      imageUrl2: "",
      //新增标题
      title: "新增产品",
      roleType: false,
      cover: "cover",
      // 显示表单
      addFromDialog: false,
      addFromDialog2: false,
      addFromDialog3: false,
      addFromDialog4: false,

      // 表格加载
      loading: false,
      //合同到期提醒
      dialogImageUrl: "",
      dialogVisible: false,
      //新增采购表格数据
      prudproducts: {
        suppliersId: "", //供应商id
        productsId: "", //产品id
        productsName: "", //产品名称
        description: "", //产品描述
        price: "", //产品价格
        model: "", //产品型号
        isIncludingTax: "", //是否含税
        number: "", //产品数量
        image: "", //产品图片
        purchaser: "", //采购人
        storageTime: "", //入库时间
        paymentType: "", //结款方式 (1现金,2月结)
        status: "", //入库状态 （0已通过，1待审核,2审核失败）
      },
      //采购入库信息
      PurchaseReceipts: {
        productsName: "", //产品名称
        purchaseOrdersId: "", //采购订单ID
        model: "", //产品型号
        price: "", //产品价格
        number: "", //产品数量
        isIncludingTax: "", //是否含税
        storageTime: "", //入库时间
        description: "", //产品描述
        image: "", //产品图片
        receiptsId: "", //入库id
        warehouseDevId: "", //仓库id
      },
      //表格数据
      tableData: [],
      // 新增员工档案信息
      addEmployeeForm: {
        id: "",
        userId: "",
        employeeName: "",
        employeeSex: 0,
        employeeBirthday: null,
        employeeAge: 0,
        employeeIdcard: "",
        employeeEmail: "",
        employeeEntryDate: "",
        employeeLeaveDate: "",
        employeeContractDate: "",
        employeeContractFile: "",
        employeeSecrecyFile: "",
        employeeStatus: 0,
        employeeUpdateStatus: 0,
        employeeUpdateCount: 0,
        createTime: "",
        updateTime: "",
      },
      //总数页
      total: 1,
      // 分页大小
      pageSize: 50,
      //记录当前页数
      currentPage: 1,
      //审核通过状态
      applyStatus: false,
      //是否含税
      SexCategory: [
        { label: "是", value: 0 },
        { label: "否", value: 1 },
      ],
      SexCategory2: [
        { label: "现金", value: 0 },
        { label: "月结", value: 1 },
      ],
      SexCategory3: [],

      //在职信息
      employeeStatusCategory: [
        { label: "在职", value: 0 },
        { label: "离职", value: 1 },
      ],
	  selectPurchase: {},
	  selectTitle: "",
	  partsShow: false,
	  suppliersId: null,
	  userId: null,
	  userLoading: false,
	  userList: [],
	  paymentMethod: null,
	  orderStatus: null,
	  suppliersLoading: false,
	  suppliersList: [],
	  applyDialog: false,
    };
  },
  mounted() {
	this.userInfo = JSON.parse(localStorage.getItem("userInfo"));
	if (this.userInfo.roleId == 1){
		this.roleType = true;
	}
    this.getAllGoods();
  },
  //超级管理员显示功能
  methods: {
    add() {
		this.$router.push({
			path: "/warehouse/purchase/addPurchase"
		})
    },
    // 查询列表
    getAllGoods() {
      this.loading = true;
	  const data = {
		  suppliersId: this.suppliersId,
		  userId: this.userId,
		  paymentMethod: this.paymentMethod,
		  orderStatus: this.orderStatus,
		  currentPage: this.currentPage,
		  pageSize: this.pageSize
	  }
	  warehouseApi.getPurchaseOrdersList(data).then(res =>{
		  if (res.code === 200){
			  this.total = res.data.total
			  this.tableData = res.data.ordersVoList.map((item, index) => {
				item.i = (this.currentPage - 1) * this.pageSize + index + 1;
				return item;
			  });
		  }
	  }).finally(() =>{
		  this.loading = false;
	  })
    },
    // pageSize变化
    handleSizeChange(pageSize) {
      this.pageSize = pageSize;
      this.getAllGoods();
    },
    // 页码变化
    handleCurrentChange(curPage) {
      this.currentPage = curPage;
      this.getAllGoods();
    },
	// 展示零件列表
	partsOpen(row){
		row.parts.forEach((part,index) =>{
			part.i = index +1
		})
		this.selectPurchase = row;
		this.selectTitle = row.suppliersName;
		this.partsShow = true;
	},
	// 关闭零件列表
	partsClose(){
		this.selectPurchase = {}
		this.selectTitle = ""
	},
	// 跳转详情页面
	details(id){
		localStorage.setItem("purchaseId", id);
		this.$router.push({
			path: "/warehouse/purchase/addPurchase"
		})
	},
	// 获取供应商列表
	getSuppliersList(query){
		this.suppliersLoading = true;
		const data = {
			suppliersName: query,
			currentPage: 1,
			pageSize: 10,
		}
		warehouseApi.getSuppliersList(data).then(res => {
			if (res.code === 200) {
				this.suppliersList = res.data.suppliersVoList
				this.suppliersLoading = false;
			}
		})
	},
	// 获取用户列表
	getUserList(query) {
		this.userLoading = true;
		const data = {
			nickName: query,
		}
		userApi.fuzzyQuery(data).then(res => {
			if (res.code === 200) {
				this.userList = res.data.userVoList
				this.userLoading = false;
			}
		})
	},
	// 重置查询条件
	reset(){
		this.suppliersId = null
		this.userId = null
		this.paymentMethod = null
		this.orderStatus = null
		this.currentPage = 1
		this.pageSize = 50
		this.getAllGoods()
	},
	// 一键入库按钮类型
	oneKeyType(receiptsStatus){
		if (receiptsStatus === "0"){
			return "success"
		}else if(receiptsStatus === "1"){
			return "warning"
		}else if(receiptsStatus === "2"){
			return "danger"
		}
		return;
	},
	// 一键入库按钮禁用
	oneKeyDisabled(row){
		if (row.orderStatus === "0"){
			if (row.receiptsStatus === null){
				return false;
			}else if (row.receiptsStatus === "2"){
				return false;
			}
		}
		return true;
	},
	// 一键入库按钮文字
	oneKeyText(receiptsStatus){
		if (receiptsStatus === "0"){
			return "入库成功"
		}else if(receiptsStatus === "1"){
			return "入库审核"
		}else if(receiptsStatus === "2"){
			return "入库失败"
		}
		return "一键入库"
	},
	// 审核按钮类型
	applyType(row){
		if (row.receiptsStatus === null && row.orderStatus !== "0"){
			if (row.orderStatus === "1"){
				return "warning";
			}
			return "danger";
		}else {
			if (row.receiptsStatus === "0"){
				return "success"
			}else if(row.receiptsStatus === "1"){
				return "warning"
			}else if(row.receiptsStatus === "2"){
				return "danger"
			}
			return;
		}

	},
	// 审核按钮禁用
	applyDisabled(row){
		if (row.receiptsStatus === null && row.orderStatus !== "0"){
			if (row.orderStatus === "1" &&
				(this.userInfo.roleId === "1" || this.userInfo.roleId === "5")){
				return false;
			}
			return true;
		}else {
			if (row.orderStatus === "0"){
				if (row.receiptsStatus === null){
					return false;
				}else if (row.receiptsStatus === "2"){
					return false;
				}
			}
			return true;
		}

	},
	// 审核按钮文字
	applyButtonText(row){
		if (row.receiptsStatus === null && row.orderStatus !== "0"){
			if (row.orderStatus === "0"){
				return "审核通过"
			}else if (row.orderStatus === "1"){
				return "待审核中"
			}
			return "审核驳回"
		}else {
			if (row.receiptsStatus === "0"){
				return "入库成功"
			}else if(row.receiptsStatus === "1"){
				return "入库审核"
			}else if(row.receiptsStatus === "2"){
				return "入库失败"
			}
			return "一键入库"
		}

	},
	// 审核弹窗打开
	applyShow(row){
		if (row.orderStatus !== "0"){
			row.parts.forEach((part,index) =>{
				part.i = index +1
			})
			this.selectPurchase = row
			this.applyDialog = true;
		}else if (row.orderStatus === "0"){
			if (row.receiptsStatus === "0"){
				this.$message.error("零件已入库")
			}else if (row.receiptsStatus === "1"){
				this.$message.warning("入库审核中")
			}
			this.$confirm("是否要一键入库？","提示",{
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() =>{
				const data = {
					id: row.id
				}
				warehouseApi.oneKeyPurchaseOrders(data).then(res =>{
					if (res.code === 200){
						this.$message.success("操作成功")
						this.getAllGoods();
					}
				})
			})
		}

	},
	applyOrders(index){
		let msg = ""
		if (index === 0){
			msg = "是否要通过订单"
		}else if (index === 2){
			msg = "是否要驳回订单"
		}
		this.$confirm(msg,"提示",{
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() =>{
			const data = {
				id: this.selectPurchase.id,
				orderStatus: index
			}
			warehouseApi.applyPurchaseOrders(data).then(res =>{
				if (res.code === 200){
					this.$message.success("操作成功");
					this.selectPurchase = {}
					this.applyDialog = false;
					this.getAllGoods();
				}
			})
		})
	},
	deletePurchasing(row){
		this.$confirm("是否要删除该订单？","提示",{
			confirmButtonText: "确定",
			cancelButtonText: "取消",
			type: "warning"
		}).then(() =>{
			const loading = this.$loading({
				lock: true,
				text: 'Loading',
				spinner: 'el-icon-loading',
				background: 'rgba(0, 0, 0, 0.7)'
			});
			warehouseApi.deletePurchasing(row).then(res =>{
				if (res.code === 200){
					this.$message.success("删除成功")
					this.getAllGoods();
				}
			}).finally(() =>{
				loading.close();
			})
		}).catch(() =>{
			
		});
	},
    // 查看零件行颜色
    tableRow({ row }) {
      //console.log("row==>", row)
      if (row.cost > row.purchasePrice) {
        return {
          background: '#cfffd7'
        };
      } else if (row.cost < row.purchasePrice) {
        return {
          background: '#ffe1e1'
        };
      }
      return {
        // background: 'oldlace'
        background: ''
      };
    },
  },
};
</script>

<style scoped>
.page {
  text-align: center;
}

.nameBox {
  overflow: auto; /* 显示滚动条 */
  z-index: 99;
  margin-top: 5px;
  font-size: 12px;
  text-align: center;
  width: 205px;
  height: 170px;
  border-radius: 5px;
  background-color: #ffffff;
  box-shadow: 0 6px 10px rgba(0, 0, 0, 0.2);
  position: absolute;
}

.purchasing{
	height: 100%;
}

.goods-table {
  height: 94%;
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  justify-content: center;
  margin-top: 10px;
}
.imgUrl {
  width: 100px;
  height: 100px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
.htimg {
  width: 150px;
  height: 150px;
  object-fit: cover; /* 保持原始宽高比，填充容器 */
}
</style>
